<template>
  <div>
    <div class="updateVideoDetailTitle">
      <van-icon name="arrow-left" style="vertical-align: -15%" @click="goBack"/>
      {{ currentStepTitle }}
    </div>
    <div class="updateVideoDetailMainPart">
      <div v-if="currentStep === 1">
        <!--上传图片区域-->
        <div class="uploadAreaTitle">
          <div
            :class="{ uploadAreaTitleContent : stepOneMaterialTypeIsPic === true , uploadAreaTitleContentDisabled : stepOneMaterialTypeIsPic === false }">
            上传图片
          </div>
          <div
            :class="{ uploadAreaTitleTip : stepOneMaterialTypeIsPic === true , uploadAreaTitleTipDisabled : stepOneMaterialTypeIsPic === false }">
            图片上限5张
          </div>
        </div>
        <div class="uploadAreaContent">
          <van-uploader v-model="picFileList1"
                        accept="image/*"
                        preview-size="2.67rem"
                        :upload-icon="stepOneMaterialTypeIsPic === true ? 'plus' : require('@/assets/img/material/disable.png')"
                        :after-read="afterReadPic"
                        :before-delete="beforeDeletePic"
                        :disabled="stepOneMaterialTypeIsPic === false"
                        :max-count="5"/>
        </div>
        <!--上传视频区域-->
        <!--        <div class="uploadAreaTitle">-->
        <!--          <div-->
        <!--            :class="{ uploadAreaTitleContent : stepOneMaterialTypeIsPic === false , uploadAreaTitleContentDisabled : stepOneMaterialTypeIsPic === true }">-->
        <!--            方式二：上传视频-->
        <!--          </div>-->
        <!--          <div-->
        <!--            :class="{ uploadAreaTitleTip : stepOneMaterialTypeIsPic === false , uploadAreaTitleTipDisabled : stepOneMaterialTypeIsPic === true }">-->
        <!--            视频上限1个-->
        <!--          </div>-->
        <!--        </div>-->
        <!--        <div class="uploadAreaContent">-->
        <!--          <div v-if="videoFileList1.length !== 0">-->
        <!--            <div class="forPreview_video"-->
        <!--                 v-for="(item, index) in videoFileList1"-->
        <!--                 :key="index">-->
        <!--                <video :src="item.content" ref="videoStepOneUVD"-->
        <!--                       :poster="item.poster" loop-->
        <!--                       @click="videoPlayOrPause"></video>-->
        <!--              <van-icon name="play-circle" size="1.2rem"-->
        <!--                        v-show="currentVideoIsPlaying === false"-->
        <!--                        class="playIcon" @click="videoPlayOrPause"/>-->
        <!--              <van-icon name="clear" size="0.43rem" class="deleteIcon" @click="deleteVideo"/>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--          <van-uploader v-model="videoFileList1"-->
        <!--                        v-if="videoFileList1.length === 0"-->
        <!--                        accept="video/*"-->
        <!--                        preview-size="2.67rem"-->
        <!--                        :upload-icon="stepOneMaterialTypeIsPic === false ? 'plus' : require('@/assets/img/material/disable.png')"-->
        <!--                        :after-read="afterReadVideo"-->
        <!--                        :disabled="stepOneMaterialTypeIsPic === true"-->
        <!--                        :max-count="1"-->
        <!--                        :max-size="30 * 1024 * 1024"-->
        <!--                        @oversize="videoIsOversize"/>-->
        <!--        </div>-->
        <!--添加文案区域-->
        <div class="uploadAreaTitle">
          <div class="uploadAreaTitleContent">文案内容</div>
          <div class="uploadAreaTitleTip">字符上限8个</div>
        </div>
        <div class="uploadAreaContent">
          <van-cell-group>
            <van-field v-model="text1" maxlength="8" clearable placeholder="请输入文案内容"/>
          </van-cell-group>
        </div>
        <!--完成-->
        <div class="completeBtnArea">
          <van-button class="completeBtn" @click="complete">保存</van-button>
        </div>
      </div>
      <div v-if="currentStep === 2">
        <!--上传图片区域-->
        <!--        <div class="uploadAreaTitle">-->
        <!--          <div-->
        <!--            :class="{ uploadAreaTitleContent : stepTwoMaterialTypeIsPic === true , uploadAreaTitleContentDisabled : stepTwoMaterialTypeIsPic === false }">-->
        <!--            方式一：上传图片-->
        <!--          </div>-->
        <!--          <div-->
        <!--            :class="{ uploadAreaTitleTip : stepTwoMaterialTypeIsPic === true , uploadAreaTitleTipDisabled : stepTwoMaterialTypeIsPic === false }">-->
        <!--            图片上限5张-->
        <!--          </div>-->
        <!--        </div>-->
        <!--        <div class="uploadAreaContent">-->
        <!--          <van-uploader v-model="picFileList2"-->
        <!--                        accept="image/*"-->
        <!--                        preview-size="2.67rem"-->
        <!--                        :upload-icon="stepTwoMaterialTypeIsPic === true ? 'plus' : require('@/assets/img/material/disable.png')"-->
        <!--                        :after-read="afterReadPic"-->
        <!--                        :before-delete="beforeDeletePic"-->
        <!--                        :disabled="stepTwoMaterialTypeIsPic === false"-->
        <!--                        :max-count="5"/>-->
        <!--        </div>-->
        <!--上传视频区域-->
        <div class="uploadAreaTitle">
          <div
            :class="{ uploadAreaTitleContent : stepTwoMaterialTypeIsPic === false , uploadAreaTitleContentDisabled : stepTwoMaterialTypeIsPic === true }">
            上传视频
          </div>
          <div
            :class="{ uploadAreaTitleTip : stepTwoMaterialTypeIsPic === false , uploadAreaTitleTipDisabled : stepTwoMaterialTypeIsPic === true }">
            视频上限1个
          </div>
        </div>
        <div class="uploadAreaContent">
          <div v-if="videoFileList2.length !== 0">
            <div class="forPreview_video"
                 v-for="(item, index) in videoFileList2"
                 :key="index">
              <video :src="item.content" ref="videoStepTwoUVD"
                     :poster="item.poster" loop
                     @click="videoPlayOrPause"></video>
              <van-icon name="play-circle" size="1.2rem"
                        v-show="currentVideoIsPlaying === false"
                        class="playIcon" @click="videoPlayOrPause"/>
              <van-icon name="clear" size="0.43rem" class="deleteIcon" @click="deleteVideo"/>
            </div>
          </div>
          <van-uploader v-model="videoFileList2"
                        v-if="videoFileList2.length === 0"
                        accept="video/*"
                        preview-size="2.67rem"
                        :upload-icon="stepTwoMaterialTypeIsPic === false ? 'plus' : require('@/assets/img/material/disable.png')"
                        :after-read="afterReadVideo"
                        :disabled="stepTwoMaterialTypeIsPic === true"
                        :max-count="1"
                        :max-size="30 * 1024 * 1024"
                        @oversize="videoIsOversize"/>
        </div>
        <div class="uploadAreaTitle">
          <van-radio-group v-model="radio2" direction="horizontal">
            <van-radio name="1">横板视频</van-radio>
            <van-radio name="0">竖版视频</van-radio>
          </van-radio-group>
        </div>
        <!--添加文案区域-->
        <div class="uploadAreaTitle">
          <div class="uploadAreaTitleContent">文案内容</div>
          <div class="uploadAreaTitleTip">字符上限8个</div>
        </div>
        <div class="uploadAreaContent">
          <van-cell-group>
            <van-field v-model="text2" maxlength="8" clearable placeholder="请输入文案内容"/>
          </van-cell-group>
        </div>
        <!--完成-->
        <div class="completeBtnArea">
          <van-button class="completeBtn" @click="complete">保存</van-button>
        </div>
      </div>
      <div v-if="currentStep === 3">
        <!--上传图片区域-->
        <!--        <div class="uploadAreaTitle">-->
        <!--          <div-->
        <!--            :class="{ uploadAreaTitleContent : stepThreeMaterialTypeIsPic === true , uploadAreaTitleContentDisabled : stepThreeMaterialTypeIsPic === false }">-->
        <!--            方式一：上传图片-->
        <!--          </div>-->
        <!--          <div-->
        <!--            :class="{ uploadAreaTitleTip : stepThreeMaterialTypeIsPic === true , uploadAreaTitleTipDisabled : stepThreeMaterialTypeIsPic === false }">-->
        <!--            图片上限5张-->
        <!--          </div>-->
        <!--        </div>-->
        <!--        <div class="uploadAreaContent">-->
        <!--          <van-uploader v-model="picFileList3"-->
        <!--                        accept="image/*"-->
        <!--                        preview-size="2.67rem"-->
        <!--                        :upload-icon="stepThreeMaterialTypeIsPic === true ? 'plus' : require('@/assets/img/material/disable.png')"-->
        <!--                        :after-read="afterReadPic"-->
        <!--                        :before-delete="beforeDeletePic"-->
        <!--                        :disabled="stepThreeMaterialTypeIsPic === false"-->
        <!--                        :max-count="5"/>-->
        <!--        </div>-->
        <!--上传视频区域-->
        <div class="uploadAreaTitle">
          <div
            :class="{ uploadAreaTitleContent : stepThreeMaterialTypeIsPic === false , uploadAreaTitleContentDisabled : stepThreeMaterialTypeIsPic === true }">
            上传视频
          </div>
          <div
            :class="{ uploadAreaTitleTip : stepThreeMaterialTypeIsPic === false , uploadAreaTitleTipDisabled : stepThreeMaterialTypeIsPic === true }">
            视频上限1个
          </div>
        </div>
        <div class="uploadAreaContent">
          <div v-if="videoFileList3.length !== 0">
            <div class="forPreview_video"
                 v-for="(item, index) in videoFileList3"
                 :key="index">
              <video :src="item.content" ref="videoStepThreeUVD"
                     :poster="item.poster" loop
                     @click="videoPlayOrPause"></video>
              <van-icon name="play-circle" size="1.2rem"
                        v-show="currentVideoIsPlaying === false"
                        class="playIcon" @click="videoPlayOrPause"/>
              <van-icon name="clear" size="0.43rem" @click="deleteVideo" class="deleteIcon"/>
            </div>
          </div>
          <van-uploader v-model="videoFileList3"
                        v-if="videoFileList3.length === 0"
                        accept="video/*"
                        preview-size="2.67rem"
                        :upload-icon="stepThreeMaterialTypeIsPic === false ? 'plus' : require('@/assets/img/material/disable.png')"
                        :after-read="afterReadVideo"
                        :disabled="stepThreeMaterialTypeIsPic === true"
                        :max-count="1"
                        :max-size="30 * 1024 * 1024"
                        @oversize="videoIsOversize"/>
        </div>
        <!--添加文案区域-->
        <div class="uploadAreaTitle">
          <van-radio-group v-model="radio3" direction="horizontal">
            <van-radio name="1">横板视频</van-radio>
            <van-radio name="0">竖版视频</van-radio>
          </van-radio-group>
        </div>
        <div class="uploadAreaTitle">
          <div class="uploadAreaTitleContent">文案内容1</div>
          <div class="uploadAreaTitleTip">字符上限8个</div>
        </div>
        <div class="uploadAreaContent">
          <van-cell-group>
            <van-field v-model="text3" maxlength="8" clearable placeholder="请输入文案内容"/>
          </van-cell-group>
        </div>
        <!--完成-->
        <div class="completeBtnArea">
          <van-button class="completeBtn" @click="complete">保存</van-button>
        </div>
      </div>
      <div v-if="currentStep === 4">
        <!--输入直播链接区域-->
        <div class="uploadAreaTitle">
          <div class="uploadAreaTitleContent">更新直播链接</div>
          <div class="uploadAreaTitleTip">添加链接上限100个</div>
        </div>
        <div class="uploadAreaContent">
          <div v-for="(item,index) in liveLinkArr" :key="index">
            <van-cell-group>
              <van-field v-model="liveLinkArr[index]"
                         :label="'链接' + (index+1)" label-width="100px"
                         type="textarea" rows="1"
                         :formatter="linkFormatter"
                         autosize placeholder="请输入链接地址">
                <template #button v-if="liveLinkArr.length > 1">
                  <van-button size="small" class="deleteLinkBtn" @click="deleteLink(index)">删除</van-button>
                </template>
                <template #button v-else>
                  <van-button size="small" class="deleteLinkBtnBlank"></van-button>
                </template>
              </van-field>
            </van-cell-group>
          </div>
        </div>
        <!--添加链接区域-->
        <div class="uploadAreaContent">
          <van-button class="addLinkBtn" @click="addLink">
            <van-icon name="plus" style="vertical-align: -15%"/>
            添加链接
          </van-button>
        </div>
        <!--添加文案区域-->
        <div class="uploadAreaTitle">
          <div class="uploadAreaTitleContent">文案内容</div>
          <div class="uploadAreaTitleTip">字符上限8个</div>
        </div>
        <div class="uploadAreaContent">
          <van-cell-group>
            <van-field v-model="text4" maxlength="8" clearable placeholder="请输入文案内容"/>
          </van-cell-group>
        </div>
        <!--完成-->
        <div class="completeBtnArea">
          <van-button class="completeBtn" @click="complete">保存</van-button>
        </div>
      </div>
      <div v-if="currentStep === 5">
        <!--选择视频封面区域-->
        <!--        <div class="uploadAreaTitle">-->
        <!--          <div class="uploadAreaTitleContent">选择视频封面</div>-->
        <!--        </div>-->
        <!--        <div class="uploadAreaContent">-->
        <!--          <div v-for="(item,index) in allUploadPic"-->
        <!--               :key="index"-->
        <!--               class="coverSelectItem"-->
        <!--               :class="{ coverSelectItemFifth: ( index + 1 ) % 5 === 0 }"-->
        <!--               @click="selectCover(index)">-->
        <!--            <img :src="item.content" class="coverSelectItemImg"-->
        <!--                 :class="{ selectedImg: item.isSelected }">-->
        <!--            <img v-if="item.isSelected"-->
        <!--                 src="@/assets/img/material/selectedTag.png"-->
        <!--                 class="selectedTag">-->
        <!--          </div>-->
        <!--        </div>-->
        <!--输入视频名称区域-->
        <!--        <div class="uploadAreaTitle">-->
        <!--          <div class="uploadAreaTitleContent">输入视频名称</div>-->
        <!--        </div>-->
        <!--        <div class="uploadAreaContent">-->
        <!--          <van-cell-group>-->
        <!--            <van-field v-model="text5" maxlength="15" clearable placeholder="请输入视频名称"/>-->
        <!--          </van-cell-group>-->
        <!--        </div>-->
        <!--选择背景音乐区域-->
        <div v-if="phoneType === 'Android'">
          <van-tabs v-model="uploadBgmType" color="#fd9800" line-width="50%" title-active-color="#fd9800">
            <van-tab title="选择背景音乐" name="选择背景音乐">
              <audio :src="currentSelectedBgm"
                     v-if="uploadBgmType === '选择背景音乐'"
                     ref="bgmPlayerUVD1"
                     hidden controls
                     loop autoplay>
              </audio>
              <div class="uploadAreaContent">
                <div class="bgmContent">
                  <div v-for="(item,index) in allBgm"
                       :key="index"
                       style="display: inline-block">
                    <div class="bgmItem"
                         :class="{ bgmItemSecond: ( index + 1 ) % 2 === 0 , selectedBgm : bgmIsSelectedArr[index]}"
                         @click="selectBgm(index)">
                      <img src="@/assets/img/material/bgmPlayIcon.png" v-if="!bgmIsSelectedArr[index]"
                           class="bgmPlayIcon">
                      <img src="@/assets/img/material/bgmPlayIconSelected.png" v-else class="bgmPlayIcon">
                      <div class="bgmName">{{ item.fileName }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </van-tab>
            <van-tab title="上传本地音乐" name="上传本地音乐">
              <div class="selectLocalBgmBtnContent">
                <div v-if="bgmFileList.length !== 0">
                  <audio v-if="uploadBgmType === '上传本地音乐'"
                         :src="bgmFileList[0].content"
                         hidden controls loop autoplay>
                  </audio>
                  <div class="showBgmArea">
                    <van-icon name="music-o" size="0.43rem" class="musicIcon"/>
                    <div class="localBgmName">{{bgmFileList[0].file.name}}</div>
                    <van-icon name="delete-o" size="0.43rem" class="deleteIcon" @click="deleteLocalBgm"/>
                  </div>
                </div>
                <van-uploader v-model="bgmFileList"
                              v-if="bgmFileList.length === 0"
                              accept=".mp3"
                              :after-read="afterReadBgm"
                              :preview-image="false"
                              :max-count="1">
                  <van-button class="selectLocalBgmBtn">选择本地音乐</van-button>
                </van-uploader>
              </div>
            </van-tab>
          </van-tabs>
        </div>
        <div v-else>
          <div class="uploadAreaTitle">
            <div class="uploadAreaTitleContent">选择背景音乐</div>
          </div>
          <audio :src="currentSelectedBgm"
                 ref="bgmPlayerUVD2"
                 hidden controls
                 loop autoplay>
          </audio>
          <div class="uploadAreaContent">
            <div class="bgmContent">
              <div v-for="(item,index) in allBgm"
                   :key="index"
                   style="display: inline-block">
                <div class="bgmItem"
                     :class="{ bgmItemSecond: ( index + 1 ) % 2 === 0 , selectedBgm : bgmIsSelectedArr[index]}"
                     @click="selectBgm(index)">
                  <img src="@/assets/img/material/bgmPlayIcon.png" v-if="!bgmIsSelectedArr[index]"
                       class="bgmPlayIcon">
                  <img src="@/assets/img/material/bgmPlayIconSelected.png" v-else class="bgmPlayIcon">
                  <div class="bgmName">{{ item.fileName }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!--完成-->
        <div class="completeBtnArea">
          <van-button class="completeBtn" @click="complete">保存</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { getToken, isAndroid } from '../../../../utilss';

export default {
  name: 'updateVideoDetail',
  data () {
    return {
      radio3: '',
      radio2: '',
      // 手机类型
      phoneType: null,
      // 当前步骤
      currentStep: 1,
      // 当前步骤名称
      currentStepTitle: '',
      // ---当前模板配置---
      currentTemplateSetting: {},
      // ---当前页面视频是否在播放---
      currentVideoIsPlaying: false,

      // 用于判断步骤1,2,3中上传文件的类型
      stepOneMaterialTypeIsPic: undefined,
      stepTwoMaterialTypeIsPic: undefined,
      stepThreeMaterialTypeIsPic: undefined,

      // 步骤一
      picFileList1: [],
      videoFileList1: [],
      text1: '',

      // 步骤二
      picFileList2: [],
      videoFileList2: [],
      // 视频上传至服务器后的地址
      videoUrl2: '',
      text2: '',

      // 步骤三
      picFileList3: [],
      videoFileList3: [],
      // 视频上传至服务器后的地址
      videoUrl3: '',
      text3: '',

      // 步骤四
      liveLinkArr: [],
      text4: '',

      // ---步骤5---
      // 所有已上传的封面图片
      allUploadPic: [],
      // 当前被选中的封面图片的下标
      currentSelectedImgIndex: undefined,
      // 视频名称
      text5: '',
      // 上传音乐方式
      uploadBgmType: '选择背景音乐',
      // 所有背景音乐
      allBgm: [],
      // 当前被选中的背景音乐的下标
      currentSelectedBgmIndex: undefined,
      // 背景音乐是否被选中
      bgmIsSelectedArr: [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false],
      // 本地上传的音乐列表
      bgmFileList: [],
      // 本地上传的音乐地址
      localBgmUrl: ''
      // videoHeight: '',
      // videoWidth: ''
    };
  },
  created () {
    // this.phoneType = isAndroid();
    // console.log(this.$route.params.step);
    // this.currentStep = this.$route.params.step;
    // this.currentTemplateSetting = this.$route.params.currentTemplateSetting;
    // this.allBgm = this.$route.params.allBgm;

    // const data = this.currentTemplateSetting;

    // if (this.currentStep === 1) {
    //   this.currentStepTitle = '更新门店信息';
    //   // 更新文件类型
    //   this.stepOneMaterialTypeIsPic = true;
    //   if (data.md !== '') {
    //     // 更新文件
    //     const imgArr = data.md.split(',');
    //     imgArr.forEach((item, index) => {
    //       if (item.includes('&')) {
    //         item = item.split('&')[0];
    //       }
    //       const splitArr = item.split('.');
    //       const imgType = splitArr[splitArr.length - 1];
    //       this.getImgToBase64(item, (res, imgTypeWH) => {
    //         const myFile = this.base64ToFile(res, 'img' + (index + 1) + '.' + imgType);
    //         this.picFileList1.push(myFile);
    //         this.allUploadPic.push({
    //           url: item,
    //           imgType: imgTypeWH
    //         });
    //       });
    //     });
    //   }
    //   // 更新文案
    //   if (data.mdText !== '') {
    //     this.text1 = data.mdText;
    //   }
    // } else if (this.currentStep === 2) {
    //   this.currentStepTitle = '更新产品信息';
    //   // 更新文件类型
    //   this.stepTwoMaterialTypeIsPic = false;
    //   if (data.cp !== '') {
    //     // 更新文件
    //     this.radio2 = data.cp.split('&')[1];
    //     data.cp = data.cp.split('&')[0];
    //     this.videoUrl2 = data.cp;
    //     const splitArr = data.cp.split('.');
    //     const videoType = splitArr[splitArr.length - 1];
    //     this.videoFileList2.push({
    //       content: data.cp,
    //       file: {
    //         name: 'cp.' + videoType
    //       },
    //       poster: `${data.cp}?vframe/jpg/offset/1.5`
    //     });
    //   }
    //   // 更新文案
    //   if (data.cpText !== '') {
    //     this.text2 = data.cpText;
    //   }
    // } else if (this.currentStep === 3) {
    //   this.currentStepTitle = '更新环境信息';
    //   // 更新文件类型
    //   this.stepThreeMaterialTypeIsPic = false;
    //   if (data.hj !== '') {
    //     // 更新文件
    //     this.radio3 = data.hj.split('&')[1];
    //     data.hj = data.hj.split('&')[0];
    //     this.videoUrl3 = data.hj;
    //     const splitArr = data.hj.split('.');
    //     const videoType = splitArr[splitArr.length - 1];
    //     this.videoFileList3.push({
    //       content: data.hj,
    //       file: {
    //         name: 'hj.' + videoType
    //       },
    //       poster: `${data.hj}?vframe/jpg/offset/1.5`
    //     });
    //   }
    //   // 更新文案
    //   if (data.hjText !== '') {
    //     this.text3 = data.hjText;
    //   }
    // } else if (this.currentStep === 4) {
    //   this.currentStepTitle = '更新直播链接';
    //   // 更新直播链接
    //   data.roomPath.split(',').forEach(item => {
    //     this.liveLinkArr.push(item);
    //   });
    //   // 更新文案
    //   if (data.roomText !== '') {
    //     this.text4 = data.roomText;
    //   }
    // } else {
    //   this.currentStepTitle = '更新背景音乐';
    //   // 更新BGM
    //   if (data.bgm !== '') {
    //     let musicType = 1;
    //     this.allBgm.forEach((item, index) => {
    //       if (item.path === data.bgm) {
    //         musicType = 0;
    //         this.currentSelectedBgmIndex = index;
    //         this.bgmIsSelectedArr[index] = true;
    //       }
    //     });
    //     if (musicType === 1 && this.phoneType === 'Android') {
    //       this.bgmFileList.push({
    //         content: data.bgm,
    //         file: {
    //           name: data.bgmName
    //         }
    //       });
    //       this.localBgmUrl = data.bgm;
    //       this.uploadBgmType = '上传本地音乐';
    //     }
    //   }
    // }
  },
  computed: {
    // 当前被选中的背景音乐的地址
    // currentSelectedBgm () {
    //   return this.currentSelectedBgmIndex === undefined ? '' : this.allBgm[this.currentSelectedBgmIndex].path;
    // }
  },
  methods: {
    goBack () {
      this.$router.push('/store/material/updateVideo');
    },

    // 步骤1,2,3 上传图片之前
    beforeRead (file) {
      if (this.allUploadPic.filter(item => item.name === file.name).length !== 0) {
        this.$toast.fail('不能重复上传相同的图片！');
        return false;
      }
      return true;
    },
    // 将图片转换为Base64
    getImgToBase64 (url, callback) {
      let canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = function () {
        // 图片是横屏还是竖屏 0-横屏 1-竖屏
        let imgType = 0;
        if (img.width >= img.height) {
          // 如果图片 宽 >= 高
        } else {
          // 如果图片 宽 < 高
          imgType = 1;
        }
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        const dataURL = canvas.toDataURL('image/jpeg');
        callback(dataURL, imgType);
        canvas = null;
      };
      img.src = url;
    },
    // 将base64转换为file类型 --> 返回与 用vant上传组件上传得到的对象 一样的格式
    base64ToFile (dataUrl, filename) {
      const arr = dataUrl.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return {
        content: dataUrl,
        file: new File([u8arr], filename, { type: mime }),
        message: '',
        status: ''
      };
    },
    // 步骤1,2,3 上传图片之后
    afterReadPic (file) {
      const _this = this;
      console.log(file);

      // 图片尺寸调整
      let canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();
      img.src = file.content;
      img.crossOrigin = 'Anonymous';
      img.onload = function () {
        let imgType = 0;
        if (img.width >= img.height) {
          // 如果图片 宽 >= 高
          canvas.width = 600;
          canvas.height = 400;
          ctx.drawImage(img, 0, 0, 600, 400);
        } else {
          // 如果图片 宽 < 高
          canvas.width = 576;
          canvas.height = 1024;
          ctx.drawImage(img, 0, 0, 576, 1024);
          imgType = 1;
        }
        // 图片尺寸调整后得到的base64
        const dataURL = canvas.toDataURL('image/jpeg');
        // 图片尺寸调整后得到的对象
        const myFile = _this.base64ToFile(dataURL, file.file.name);
        // 上传图片至服务器，获取图片地址
        const uploadScForm = new FormData();
        uploadScForm.append('file', myFile.file);
        _this.$toast.loading(
          {
            duration: 0,
            message: '加载中...',
            overlay: true
          }
        );
        axios.post(`${process.env.VUE_APP_BASEAPI}upload/logo`, uploadScForm, {
          headers: {
            'Content-Type': 'multipart/form-data',
            session_id: getToken()
          }
        }).then(res => {
          _this.$toast.clear();
          const result = res.data;
          if (result.code === 0) {
            const url = result.data;
            console.log('上传图片成功-->' + url);
            _this.picFileList1.pop();
            _this.picFileList1.push(myFile);
            // 将上传的图片放入数组allUploadPic中
            _this.allUploadPic.push({
              url: url,
              imgType: imgType
            });
            canvas = null;
          } else {
            console.log('上传图片失败！');
            _this.$toast.fail('加载失败，请重试！');
          }
        }).catch(() => {
          _this.$toast.clear();
          console.log('上传图片失败！');
          _this.$toast.fail('加载失败，请重试！');
        });
      };
    },
    // 步骤1,2,3 删除图片之前
    beforeDeletePic (file, detail) {
      // detail.index代表图片的索引
      const fileIndex = detail.index;
      if (this.currentStep === 1) {
        this.picFileList1.splice(fileIndex, 1);
      } else if (this.currentStep === 2) {
        this.picFileList2.splice(fileIndex, 1);
      } else {
        this.picFileList3.splice(fileIndex, 1);
      }
      this.allUploadPic.splice(fileIndex, 1);
    },
    // 步骤1,2,3 上传视频之前-->用于获取视频的宽高
    async beforeReadVideo (file) {
      console.log(file, '-->file');
      // this.$toast({
      //   message: `file.type: ${file.type}`,
      //   duration: 10000
      // });
      // return this.uploadVideoSizeAsync({ file });
    },
    // uploadVideoSizeAsync ({ file }) {
    //   return new Promise((resolve, reject) => {
    //     this.uploadVideoSize(file, (res) => {
    //       if (res.videoWidth > res.videoHeight) {
    //         this.$toast('为了生成视频的美观，请保证上传的视频为竖屏视频！');
    //         // eslint-disable-next-line prefer-promise-reject-errors
    //         return reject();
    //       }
    //       return resolve();
    //     });
    //   });
    // },
    // uploadVideoSize (file, callBack) {
    //   const myVideo = document.createElement('video');
    //   myVideo.src = URL.createObjectURL(file);
    //   myVideo.addEventListener('loadedmetadata', () => {
    //     return callBack({
    //       videoWidth: myVideo.videoWidth,
    //       videoHeight: myVideo.videoHeight
    //     });
    //   });
    // },
    // 步骤1,2,3 上传视频之后
    afterReadVideo (file) {
      console.log(file, 'afterReadVideo');
      // 上传视频至服务器，获取视频地址
      // const androidVideo = document.getElementsByTagName('video');
      // this.$nextTick(() => {
      //   console.log(androidVideo[0].clientHeight, androidVideo[0].clientWidth);
      //   this.videoHeight = androidVideo[0].clientHeight;
      //   this.videoWidth = androidVideo[0].clientWidth;
      // });
      const uploadScForm = new FormData();
      uploadScForm.append('file', file.file);
      this.$toast.loading(
        {
          duration: 0,
          message: '加载中...',
          overlay: true
        }
      );
      axios.post(`${process.env.VUE_APP_BASEAPI}upload/logo`, uploadScForm, {
        headers: {
          'Content-Type': 'multipart/form-data',
          session_id: getToken()
        }
      }).then(res => {
        this.$toast.clear();
        const result = res.data;
        if (result.code === 0) {
          const url = result.data;
          console.log('上传视频成功-->' + url);

          // 将上传的视频地址保存
          if (this.currentStep === 2) {
            this.radio2 = '';
            this.videoUrl2 = url;
          }
          if (this.currentStep === 3) {
            this.radio3 = '';
            this.videoUrl3 = url;
          }
        } else {
          console.log('上传视频失败！');
          this.$toast.fail('加载失败，请重试！');
        }
      }).catch(() => {
        this.$toast.clear();
        console.log('上传视频失败！');
        this.$toast.fail('加载失败，请重试！');
      });
    },
    // 步骤1,2,3 判断视频是否超过限制大小
    videoIsOversize (file) {
      console.log(file);
      this.$toast('视频大小不能超过 30MB');
    },
    // 步骤1,2,3 视频播放/暂停
    videoPlayOrPause () {
      if (this.currentStep === 1) {
        const currentVideo = this.$refs.videoStepOneUVD[0];
        if (currentVideo.paused === true) {
          this.currentVideoIsPlaying = true;
          currentVideo.play();
        } else {
          this.currentVideoIsPlaying = false;
          currentVideo.pause();
        }
      } else if (this.currentStep === 2) {
        const currentVideo = this.$refs.videoStepTwoUVD[0];
        if (currentVideo.paused === true) {
          this.currentVideoIsPlaying = true;
          currentVideo.play();
        } else {
          this.currentVideoIsPlaying = false;
          currentVideo.pause();
        }
      } else {
        const currentVideo = this.$refs.videoStepThreeUVD[0];
        if (currentVideo.paused === true) {
          this.currentVideoIsPlaying = true;
          currentVideo.play();
        } else {
          this.currentVideoIsPlaying = false;
          currentVideo.pause();
        }
      }
    },
    // 步骤1,2,3 删除视频
    deleteVideo () {
      if (this.currentStep === 1) {
        this.videoFileList1 = [];
      } else if (this.currentStep === 2) {
        this.videoFileList2 = [];
      } else {
        this.videoFileList3 = [];
      }
    },
    // 完成
    async complete () {
      // if (this.radio2 || this.radio3) {
      //   this.$toast.fail('请选择视频类型！');
      //   return;
      // }
      const uploadTemplateForm = new FormData();
      uploadTemplateForm.append('organId', this.$store.state.userInfo.organId);

      if (this.currentStep === 1) {
        // 门店文件 地址/类型
        if (this.picFileList1.length !== 0) {
          const filePaths = [];
          this.allUploadPic.forEach(item => {
            filePaths.push(item.url + '&' + item.imgType);
          });
          uploadTemplateForm.append('mdFilePaths', filePaths.join(','));
          uploadTemplateForm.append('mdFileType', 'img');
        } else {
          uploadTemplateForm.append('mdFilePaths', '');
          uploadTemplateForm.append('mdFileType', '');
        }
        // 门店文案
        uploadTemplateForm.append('mdFileText', this.text1);
      } else if (this.currentStep === 2) {
        // 产品文件 地址/类型
        if (!this.radio2) {
          this.$toast.fail('请选择视频类型！');
          return;
        }
        if (this.videoFileList2.length !== 0) {
          if (this.radio2 === '1') {
            // 横屏
            this.videoUrl2 = this.videoUrl2 + '&1';
          } else {
            // 竖屏
            this.videoUrl2 = this.videoUrl2 + '&0';
          }
          uploadTemplateForm.append('cpFilePaths', this.videoUrl2);
          uploadTemplateForm.append('cpFileType', 'video');
        } else {
          uploadTemplateForm.append('cpFilePaths', '');
          uploadTemplateForm.append('cpFileType', '');
        }
        // 产品文案
        uploadTemplateForm.append('cpFileText', this.text2);
      } else if (this.currentStep === 3) {
        // 环境文件 地址/类型
        if (!this.radio3) {
          this.$toast.fail('请选择视频类型！');
          return;
        }
        if (this.videoFileList3.length !== 0) {
          if (this.radio3 === '1') {
            // 横屏
            this.videoUrl3 = this.videoUrl3 + '&1';
          } else {
            // 竖屏
            this.videoUrl3 = this.videoUrl3 + '&0';
          }
          uploadTemplateForm.append('hjFilePaths', this.videoUrl3);
          uploadTemplateForm.append('hjFileType', 'video');
        } else {
          uploadTemplateForm.append('hjFilePaths', '');
          uploadTemplateForm.append('hjFileType', '');
        }
        // 环境文案
        uploadTemplateForm.append('hjFileText', this.text3);
      } else if (this.currentStep === 4) {
        if (this.liveLinkArr[0] === '') {
          this.$toast.fail('请先输入直播链接！');
          return false;
        }
        // 直播间地址
        uploadTemplateForm.append('roomPaths', this.liveLinkArr.join(','));
        // 直播间文案
        uploadTemplateForm.append('roomText', this.text4);
      } else {
        if (this.uploadBgmType === '选择背景音乐' && this.currentSelectedBgmIndex !== undefined) {
          // 背景音乐名称
          uploadTemplateForm.append('bgmName', this.allBgm[this.currentSelectedBgmIndex].fileName);
          // 背景音乐地址
          uploadTemplateForm.append('bgmPath', this.allBgm[this.currentSelectedBgmIndex].path);
        } else if (this.uploadBgmType === '上传本地音乐' && this.bgmFileList.length !== 0) {
          // 背景音乐名称
          uploadTemplateForm.append('bgmName', this.bgmFileList[0].file.name);
          // 背景音乐地址
          uploadTemplateForm.append('bgmPath', this.localBgmUrl);
        } else {
          // 背景音乐名称
          uploadTemplateForm.append('bgmName', '');
          // 背景音乐地址
          uploadTemplateForm.append('bgmPath', '');
        }
      }

      axios.post(`${process.env.VUE_APP_BASEAPI}upload/activity/sc`, uploadTemplateForm, {
        headers: {
          'Content-Type': 'multipart/form-data',
          session_id: getToken()
        }
      }).then(res => {
        console.log(res.data);
        if (res.data.code === 0) {
          this.$toast.success('保存素材成功，请返回确认更新！');
          const stepObj = {
            organId: this.$store.state.userInfo.organId,
            step: this.currentStep
          };
          this.$store.commit('setChangedStep', stepObj);
          setTimeout(() => {
            this.$router.push('/store/material/updateVideo');
          }, 1000);
        } else {
          this.$toast.fail('上传素材失败！');
        }
      }).catch(() => {
        this.$toast.fail('上传素材失败！');
      });
    },

    // ---步骤4---
    // 格式化链接
    linkFormatter (value) {
      const httpsIndex = value.search('https://v.douyin.com/');
      const result = value.slice(httpsIndex);
      return result;
    },
    // 添加链接
    addLink () {
      this.liveLinkArr.push('');
    },
    // 删除链接
    deleteLink (index) {
      this.liveLinkArr.splice(index, 1);
    },

    // 步骤5 选择封面图片
    selectCover (index) {
      if (this.currentSelectedImgIndex !== index) {
        if (this.currentSelectedImgIndex !== undefined) {
          this.$set(this.allUploadPic[this.currentSelectedImgIndex], 'isSelected', false);
        }
        this.$set(this.allUploadPic[index], 'isSelected', true);
        this.currentSelectedImgIndex = index;
      }
    },
    // 步骤5 选择背景音乐
    selectBgm (index) {
      let bgm = null;
      if (this.phoneType === 'Android') {
        bgm = this.$refs.bgmPlayerUVD1;
      } else {
        bgm = this.$refs.bgmPlayerUVD2;
      }
      if (this.currentSelectedBgmIndex !== index) {
        if (this.currentSelectedBgmIndex !== undefined) {
          this.$set(this.bgmIsSelectedArr, this.currentSelectedBgmIndex, false);
        }
        this.$set(this.bgmIsSelectedArr, index, true);
        this.currentSelectedBgmIndex = index;
        this.$nextTick(() => bgm.play());
      } else {
        this.$set(this.bgmIsSelectedArr, index, false);
        this.currentSelectedBgmIndex = undefined;
        // if (bgm.paused) {
        //   bgm.play();
        // } else {
        //   bgm.pause();
        // }
      }
    },
    // 步骤5 上传本地音乐之后
    afterReadBgm (file) {
      console.log(file);
      const uploadBgmForm = new FormData();
      uploadBgmForm.append('file', file.file);
      this.$toast.loading(
        {
          duration: 0,
          message: '加载中...',
          overlay: true
        }
      );
      axios.post(`${process.env.VUE_APP_BASEAPI}upload/logo`, uploadBgmForm, {
        headers: {
          'Content-Type': 'multipart/form-data',
          session_id: getToken()
        }
      }).then(res => {
        this.$toast.clear();
        const result = res.data;
        if (result.code === 0) {
          console.log('上传BGM成功！');
          this.localBgmUrl = result.data;
        } else {
          console.log('上传BGM失败！');
          this.$toast.fail('加载失败，请重试！');
        }
      }).catch(() => {
        this.$toast.clear();
        console.log('上传BGM失败！');
        this.$toast.fail('加载失败，请重试！');
      });
    },
    // 步骤5 删除上传的本地音乐
    deleteLocalBgm () {
      this.bgmFileList = [];
      this.localBgmUrl = '';
    }
  }
};
</script>

<style scoped>
  .updateVideoDetailTitle {
    height: 44px;
    padding-left: 20px;
    color: #333333;
    font-size: 14px;
    line-height: 44px;
  }

  .updateVideoDetailMainPart {
    margin-bottom: 50px;
    padding: 0 20px;
    line-height: 20px;
  }

  .uploadAreaTitle {
    margin-top: 10px;
  }

  .uploadAreaTitleContent {
    display: inline-block;
    color: #666666;
    font-size: 12px;
  }

  .uploadAreaTitleContentDisabled {
    display: inline-block;
    color: #D9D9D9;
    font-size: 12px;
  }

  .uploadAreaTitleTip {
    color: #999999;
    font-size: 12px;
    float: right;
    transform: scale(0.83);
    margin-right: -6px;
  }

  .uploadAreaTitleTipDisabled {
    color: #D9D9D9;
    font-size: 12px;
    float: right;
    transform: scale(0.83);
    margin-right: -6px;
  }

  .uploadAreaContent {
    margin-top: 10px;
  }

  /deep/ .van-uploader__upload {
    width: 100px !important;
    height: 100px !important;
  }

  /deep/ .van-uploader__preview-image {
    width: 100px !important;
    height: 100px !important;
  }

  .completeBtnArea {
    margin-top: 25px;
    text-align: center;
  }

  .completeBtn {
    color: #FFFFFF;
    font-size: 16px;
    padding: 10px 18px;
    border: 1px solid #fd9800;
    border-radius: 4px;
    background-color: #fd9800;
  }

  /deep/ .van-cell {
    font-size: 12px;
  }

  .addLinkBtn {
    width: 100%;
    background: #FAFAFA;
    border: 1px solid #FAFAFA;
    font-size: 12px;
  }

  .coverSelectItem {
    display: inline-block;
    position: relative;
    width: 50px;
    height: 50px;
    margin: 0 21px 10px 0;
  }

  .coverSelectItemFifth {
    margin: 0 0 10px 0;
  }

  .coverSelectItemImg {
    width: 50px;
    height: 50px;
    border-radius: 4px;
    border: 1px solid #ffffff;
  }

  .selectedImg {
    border: 1px solid #fd9800;
  }

  .selectedTag {
    position: absolute;
    top: 5px;
    right: 5px;
    width: 14px;
    height: 14px;
  }

  .bgmType {
    color: #999999;
  }

  .myDot {
    display: inline-block;
    width: 6px;
    height: 6px;
    background: #C4C4C4;
    border-radius: 3px;
    vertical-align: 1px;
    margin-right: 5px;
  }

  .bgmContent {
    margin-top: 5px;
  }

  .bgmItem {
    width: 133px;
    height: 23px;
    line-height: 23px;
    background: #F5F5F5;
    padding: 0 10px;
    border: 1px solid #F5F5F5;
    border-radius: 4px;
    color: #999999;
    margin: 0 21px 10px 0;
  }

  .bgmItemSecond {
    margin: 0 0 10px 0;
  }

  .selectedBgm {
    color: #fd9800;
    background: #FFFFFF;
    border: 1px solid #fd9800;
  }

  .bgmPlayIcon {
    width: 16px;
    height: 16px;
    margin-right: 10px;
    vertical-align: 3px;
  }

  .bgmName {
    display: inline-block;
    width: 2.8rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  video {
    width: 100%;
    background: #000000;
  }

  .forPreview_video {
    position: relative;
    color: #FFFFFF;
  }

  .playIcon {
    position: absolute;
    bottom: 10px;
    left: 5px;
  }

  .deleteIcon {
    position: absolute;
    right: 5px;
    top: 5px;
  }

  /deep/ .van-field__label {
    line-height: 0.87rem !important;
  }

  .deleteLinkBtn {
    color: #FFFFFF;
    border: 1px solid #fd9800;
    border-radius: 4px;
    background-color: #fd9800;
  }

  .deleteLinkBtnBlank {
    border: 0;
  }

  .selectLocalBgmBtnContent {
    margin-top: 20px;
    text-align: center;
  }

  .selectLocalBgmBtn {
    width: 300px;
    color: #FFFFFF;
    border: 1px solid #fd9800;
    border-radius: 30px;
    background-color: #fd9800;
  }

  .showBgmArea {
    display: inline-block;
    position: relative;
    width: 300px;
    font-size: 14px;
    color: #FFFFFF;
    padding: 15px;
    border: 1px solid #fd9800;
    border-radius: 30px;
    background-color: #fd9800;
  }

  .musicIcon {
    position: absolute;
    top: 17px;
    left: 15px;
    vertical-align: -15%;
  }

  .localBgmName {
    display: inline-block;
    width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .deleteIcon {
    position: absolute;
    top: 17px;
    right: 15px;
    vertical-align: -15%;
  }
</style>
